package com.heatup.apt.api.controller;

import com.heatup.apt.api.service.AccessService;
import com.heatup.apt.api.service.MyBooksService;
import com.heatup.apt.common.constants.ErrorCodeConstants;
import com.heatup.apt.common.constants.ServiceConstans.ServiceType;
import com.heatup.apt.common.exception.OrderNotFoundException;
import com.heatup.apt.common.util.JsonTools;
import com.heatup.apt.common.util.RequestTools;
import com.heatup.apt.common.util.ResponseTools;
import com.heatup.apt.model.api.ApiResultModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by b3st9u on 16/8/29.
 */
@RequestMapping(value = "/mybook")
@Controller
public class MyBookController extends BaseController {

    @Resource
    private MyBooksService myBooksService;

    @Resource
    private AccessService accessService;

    private static final Logger logger = LoggerFactory.getLogger(MyBookController.class);

    /**
     * orderStatus订单状态(1正常 2取消,3排队，4完成)，serviceType服务类型(1团课订单 2私教订单 3檬营订单 4自助健身,5会员订单)
     *
     * @param request
     * @param campType (檬营排队订单类型 1未成营排队 2爆仓排队)
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/get", method = {RequestMethod.POST, RequestMethod.GET})
    private String getMyBookResult(HttpServletRequest request, Integer campType) {
        //订单状态
        int orderStatus = RequestTools.RequestInt(request, "orderStatus", 0);
        //服务类型
        int serviceType = RequestTools.RequestInt(request, "serviceType", 0);

        String callback = RequestTools.RequestString(request, "callback", "");

        ApiResultModel<Map<String, Object>> apiResultModel = new ApiResultModel<Map<String, Object>>();
        apiResultModel.setLogined(this.isLogined());

        //未登陆
        if (!isLogined()) {
            apiResultModel.setRet(ApiResultModel.RET_ERROR);
            apiResultModel.setErrorCode(ErrorCodeConstants.Code.USER_NOT_LOGIN.getCode());
            apiResultModel.setMsg(ErrorCodeConstants.Code.USER_NOT_LOGIN.getMessage());
            return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
        }

        try {
            int userId = this.getUserId();
            List<Map<String, Object>> map = myBooksService.getMyBooks(orderStatus, serviceType, userId, campType);

            Map<String, Object> result = new HashMap<>();

            //取得每种类型的个数 maxxiang add
            int teamCourseCount = myBooksService.getMyBooksCount(orderStatus, ServiceType.teamCourse.getIndex(), userId, null);
            int selfFitnessCount = myBooksService.getMyBooksCount(orderStatus, ServiceType.selfFitness.getIndex(), userId, null);
            int privateCourseCount = myBooksService.getMyBooksCount(orderStatus, ServiceType.privateCourse.getIndex(), userId, null);
            //檬营已成营订单个数
            int campCourseCount = myBooksService.getMyBooksCount(1, ServiceType.campCourse.getIndex(), userId, null);
            //檬营未成营(排队)订单
            if (orderStatus == 3) {
                result.put("campCourseNotYetCount", myBooksService.getMyBooksCount(orderStatus, ServiceType.campCourse.getIndex(), userId, 1));
            }
            //檬营已成营爆仓(排队)订单
            if (orderStatus == 3) {
                result.put("campCourseOverCount", myBooksService.getMyBooksCount(orderStatus, ServiceType.campCourse.getIndex(), userId, 2));
            }

            result.put("teamCourseCount", teamCourseCount);
            result.put("selfFitnessCount", selfFitnessCount);
            result.put("privateCourseCount", privateCourseCount);
            result.put("campCourseCount", campCourseCount);

            result.put("list", map);

            apiResultModel.setData(result);
            apiResultModel.setRet(ApiResultModel.RET_SUCCESS);

            if (map == null || map.size() == 0) {
                apiResultModel.setMsg("暂无");
                apiResultModel.setErrorCode(ErrorCodeConstants.Code.NO_DATA_FOUND.getCode());
            }

        } catch (Exception e) {
            e.printStackTrace();
            apiResultModel.setRet(ApiResultModel.RET_ERROR);
            apiResultModel.setErrorCode(ErrorCodeConstants.Code.SYSTEM_ERROR_EXCEPTION.getCode());
            apiResultModel.setMsg(ErrorCodeConstants.Code.SYSTEM_ERROR_EXCEPTION.getMessage() + "_" + e.toString() + e.getCause());
            logger.error(ErrorCodeConstants.Code.SYSTEM_ERROR_EXCEPTION.getMessage() + "_" + e.toString() + e.getCause(), e);
        }
        return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
    }

    /**
     * 订单详情 (订单付款成功后 请求订单结果接口)
     *
     * @author blank 2017/8/11 下午6:55
     */
    @ResponseBody
    @RequestMapping(value = "/detail", method = {RequestMethod.POST, RequestMethod.GET})
    private String getMyBookDetail(HttpServletRequest request) {
        int orderId = RequestTools.RequestInt(request, "orderId", 0);
        String callback = RequestTools.RequestString(request, "callback", "");
        ApiResultModel<Map<String, Object>> apiResultModel = new ApiResultModel<Map<String, Object>>();
        apiResultModel.setLogined(this.isLogined());
        //未登陆
        if (!isLogined()) {
            apiResultModel.setRet(ApiResultModel.RET_ERROR);
            apiResultModel.setErrorCode(ErrorCodeConstants.Code.USER_NOT_LOGIN.getCode());
            apiResultModel.setMsg(ErrorCodeConstants.Code.USER_NOT_LOGIN.getMessage());
            return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
        }
        Map<String, Object> map = new HashMap<>();
        try {
            int userId = this.getUserId();
            map = myBooksService.orderDetail(orderId, userId);//myBooksService.getMyBookDetail(orderId, userId);
            if (map.size() == 0 || map == null) {
                apiResultModel.setErrorCode(ErrorCodeConstants.Code.NO_DATA_FOUND.getCode());
            }
            apiResultModel.setData(map);
            apiResultModel.setRet(ApiResultModel.RET_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            apiResultModel.setRet(ApiResultModel.RET_ERROR);
            apiResultModel.setErrorCode(ErrorCodeConstants.Code.SYSTEM_ERROR_EXCEPTION.getCode());
            apiResultModel.setMsg(ErrorCodeConstants.Code.SYSTEM_ERROR_EXCEPTION.getMessage() + "_" + e.toString() + e.getCause());
            logger.error(ErrorCodeConstants.Code.SYSTEM_ERROR_EXCEPTION.getMessage() + "_" + e.toString() + e.getCause(), e);
        }
        return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
    }

    /**
     * 获取分享权限签名
     * 必须传入分享的路径，并且必须是完整的路径
     *
     * @return
     */

    @ResponseBody
    @RequestMapping(value = ("/weiXinShare"))
    public String getSign(HttpServletRequest request, HttpServletResponse response) {
        String URL = RequestTools.RequestString(request, "url", "");
        String invalid = RequestTools.RequestString(request, "invalid", null);
        String callback = RequestTools.RequestString(request, "callback", "");
        ApiResultModel<Map<String, String>> apiResultModel = myBooksService.getSing(URL, invalid);
        apiResultModel.setLogined(isLogined());
        return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
    }


    /**
     * 根据订单 ID 返回 新的有效期2分钟的二维码
     *
     * @param orderId  订单 ID
     * @param callback js 回调
     * @return 新的有效期2分钟的二维码
     * @author blank 2017/11/1 上午10:36
     */
    @RequestMapping("getNewQRCode")
    @ResponseBody
    public String getMyOrderNewQRCode(@RequestParam Integer orderId, String callback) {

        ApiResultModel<Map<String, Object>> apiResultModel = new ApiResultModel<>(isLogined());
        if (!apiResultModel.isLogined()) {
            //未登陆
            apiResultModel.setRet(ApiResultModel.RET_ERROR);
            apiResultModel.setErrorCode(ErrorCodeConstants.Code.USER_NOT_LOGIN.getCode());
            apiResultModel.setMsg(ErrorCodeConstants.Code.USER_NOT_LOGIN.getMessage());
            return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);

        }

        try {
            apiResultModel.setData(accessService.updateAndGetNewQRCodeByOrderId(orderId));
        } catch (OrderNotFoundException e) {
            e.printStackTrace();
            apiResultModel.setRet(ApiResultModel.RET_ERROR);
            apiResultModel.setErrorCode(ErrorCodeConstants.Code.SYSTEM_ERROR_EXCEPTION.getCode());
            apiResultModel.setMsg(ErrorCodeConstants.Code.SYSTEM_ERROR_EXCEPTION.getMessage() + "_" + e.toString() + e.getCause());
            logger.error(ErrorCodeConstants.Code.SYSTEM_ERROR_EXCEPTION.getMessage() + "_" + e.toString() + e.getCause(), e);
        }

        return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);

    }
    
    /**
     * 获取用户私教咨询订单列表
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping("/get_consult_order")
    public String getConsultOrder(HttpServletRequest request, HttpServletResponse response) {
    	ApiResultModel<Map<String, Object>> apiResultModel = new ApiResultModel<>(isLogined());
    	Map<String,Object> resultMap = new HashMap<>();
    	String callback = RequestTools.RequestString(request, "callback", "");
    	Integer userId = this.getUserId();
    	try {
    		resultMap = myBooksService.queryUserPrivateConsultOrderDetailListByUserId(userId);
    		apiResultModel.setData(resultMap);
    		apiResultModel.setRet(ApiResultModel.RET_SUCCESS);
    		apiResultModel.setMsg(" 查询成功！");
		} catch (Exception e) {
			// TODO: handle exception
			apiResultModel.setData(resultMap);
    		apiResultModel.setRet(ApiResultModel.RET_ERROR);
    		apiResultModel.setMsg(" 查询失败！");
    		logger.error("=========== getConsultOrder error:"+e.toString()+e.getCause(),e);
		}
    	return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
    }


}
